// composables/useOrderWebSocket.ts
import { ref, onMounted, onUnmounted } from 'vue';
import url from '@/config';
import { useOrderStore } from '@/store/modules/order';

// 数据定义
let useStore = useOrderStore();
export function useOrderWebSocket() {
	//const orderList = ref([]);
	// WebSocket
	const serverUrl = url.wsURL + uni.getStorageSync('refreshToken');
	let ws: WebSocket | null = null;
	const reconnectInterval = ref<NodeJS.Timeout>();
	const initWebSocket = () => {
		// 创建 WebSocket 连接
		ws = new WebSocket(serverUrl);
		ws.onopen = (e) => {
			console.log('websockert 已连接！');
		};
		ws.onmessage = (e) => {
			const message = JSON.parse(e.data);
			if ((message.type = 'order')) {
				let data = message.content;
				console.log('recieve order==', JSON.parse(data));
				useStore.addOrder(JSON.parse(data));
				//语言播报
				handleNoticeBreakfast();
			}
		};

		ws.onclose = () => {
			console.log('websockert 已断开！');
			reconnectInterval.value = setInterval(() => {
				if (!ws || ws.readyState === WebSocket.CLOSED) {
					initWebSocket();
				}
			}, 5000);
		};
	};
	onMounted(initWebSocket);
	onUnmounted(() => ws?.close());
}
// 处理消息的方法
const handleNoticeBreakfast = () => {
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	innerAudioContext.src = 'https://www.h321.site/order.mp3';
	innerAudioContext.loop = false;
	innerAudioContext.onCanplay(() => {
		innerAudioContext.play();
	});
	innerAudioContext.onError((res) => {
		console.error('音频播放失败:', res);
	});
};
